package util

import (
	"database/sql"
	"fmt"
	"github.com/jmoiron/sqlx"
	"strings"
)

type OracleColumnInfo struct {
	ColumnName    string         `db:"COLUMN_NAME" json:"ColumnName"`
	DataType      string         `db:"DATA_TYPE" json:"DataType"`
	DataLength    int            `db:"DATA_LENGTH" json:"DataLength"`
	DataPrecision sql.NullInt32  `db:"DATA_PRECISION" json:"DataPrecision"`
	Nullable      string         `db:"NULLABLE" json:"Nullable"`
	DataDefault   sql.NullString `db:"DATA_DEFAULT" json:"DataDefault"`
}

type OracleTableComment struct {
	Comments string `db:"COMMENTS" json:" Comments"`
}

type OracleColumnComment struct {
	ColumnName string `db:"COLUMN_NAME" json:"ColumnName"`
	Comments   string `db:"COMMENTS" json:"Comments"`
}

func ReplaceOracleQuestion(s string) string {
	parts := strings.Split(s, "?")
	for i := 1; i < len(parts); i++ {
		parts[0] += fmt.Sprintf(":%d", i) + parts[i]
	}
	return parts[0]
}

func QueryOracleTableColumns(db *sqlx.DB, tableName string) ([]OracleColumnInfo, error) {
	query := `
        SELECT
            COLUMN_NAME,
            DATA_TYPE,
            DATA_LENGTH,
            DATA_PRECISION,
            NULLABLE,
            DATA_DEFAULT
        FROM
            ALL_TAB_COLUMNS
        WHERE
            TABLE_NAME = :1
    `

	var columns []OracleColumnInfo
	err := db.Select(&columns, query, tableName)
	if err != nil {
		return nil, err
	}

	return columns, nil
}

func QueryOracleTableComment(db *sqlx.DB, tableName string) (OracleTableComment, error) {
	query := `
        SELECT
            COMMENTS
        FROM
            ALL_TAB_COMMENTS
        WHERE
            TABLE_NAME = :1
    `

	var comment OracleTableComment
	err := db.QueryRow(query, tableName).Scan(&comment.Comments)
	if err != nil {
		return OracleTableComment{}, err
	}

	return comment, nil
}

func QueryOracleColumnComments(db *sqlx.DB, tableName string) ([]OracleColumnComment, error) {
	// 还可以 DBA_COL_COMMENTS   USER_COL_COMMENTS (不行)
	query := `
        SELECT
            COLUMN_NAME,
            COMMENTS
        FROM
            ALL_COL_COMMENTS
        WHERE
            TABLE_NAME = :1
    `
	var comments []OracleColumnComment
	err := db.Select(&comments, query, tableName)
	if err != nil {
		return nil, err
	}
	return comments, nil
}
